package com.liuwang.meal.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.liuwang.meal.adapter.DateAdapter;
import com.liuwang.meal.bean.Menu;
import com.liuwang.meal.bean.MenuType;
import com.liuwang.meal.bean.User;
import com.liuwang.meal.manager.MenuManager;
import com.liuwang.meal.manager.MenuTypeManager;
import com.liuwang.meal.manager.OrderDetailManager;
import com.liuwang.meal.manager.UserManager;
import com.liuwang.meal.util.MyApplication;
import com.liuwang.meal.util.MyUtil;
import com.liuwang.meal.util.ScrollLayout;
import com.liuwang.meal.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MenuActivity extends Activity {
	/** 总页数. */
	private int PageCount;
	/** 当前页码. */
	private int PageCurrent;
	/** 被选中的. */
	private int gridID = -1;
	/** 每页显示的数量，Adapter保持一致. */
	private static final float PAGE_SIZE = 12.0f;
	/** GridView. */
	private GridView gridView;
	/** 自定义的左右滑动. */
	private ScrollLayout curPage;
	/** 页码条布局、菜品类型. */
	private LinearLayout layoutBottom,menuTypes;
	/** 页码条. */
	private ImageView imgCur;
	/** 数据集. */
	private List<MenuType> lstDate_MenuType = new ArrayList<MenuType>();
	private List<Menu> lstDate = new ArrayList<Menu>();
	private List<Button> button_menuTypes = new ArrayList<Button>();
	/** 菜品描述. */
	private TextView textview_menuDesc;
	/** 跳转到订单页面按钮. */
	private Button button_toOrder;
	/** 呼叫前台. */
//	private ImageButton imageButton_call;
	/** 选中的菜单类型ID. */
	private Integer type_id=1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		MyApplication.getInstance().addActivity(this);//添加当前Activity到Activity容器
		
		findViews();
		initViews();
		
		curPage.setPageListener(new ScrollLayout.PageListener() {
			@Override
			public void page(int page) {
				setCurPage(page);
			}
		});
		
		//字体闪烁动画，使用线程和Timer实现
		spark();  
	}

	//字体闪烁动画，使用线程和Timer实现
	private int clo = 0;
	public void spark() {
		final Button touchScreen = (Button) findViewById(R.id.button_toOrder);// 获取页面textview对象
		Timer timer = new Timer();
		TimerTask taskcc = new TimerTask(){

			public void run() {
				runOnUiThread(new Runnable() {
					public void run() {
						if (clo == 0) {
							clo = 1;
							touchScreen.setTextColor(Color.RED); // 透明Color.TRANSPARENT
						} else {
								clo = 0;
								touchScreen.setTextColor(Color.BLUE);
						}
					}
				});
			}
		};
		timer.schedule(taskcc, 1, 2000); // 参数分别是delay（多长时间后执行），duration（执行间隔）
	}
	
	/**
	 * 初始化
	 */
	private void findViews() {
		curPage = (ScrollLayout) findViewById(R.id.scr);
		layoutBottom = (LinearLayout) findViewById(R.id.layout_scr_bottom);
		textview_menuDesc=(TextView) findViewById(R.id.textview_menuDesc);
		menuTypes = (LinearLayout) findViewById(R.id.menuTypes);
		curPage.getLayoutParams().height = this.getWindowManager().getDefaultDisplay().getHeight() * 7 / 8;
		button_toOrder = (Button) findViewById(R.id.button_toOrder);
//		imageButton_call = (ImageButton) findViewById(R.id.imageButton_call);
	}
	
	/**
	 * 初始化
	 */
	private void initViews() {
		
		initViews_Menu(1);
		
		// 初始化菜品类型
		initViews_MenuType();
		

		//跳转订单页面
		button_toOrder.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MenuActivity.this, OrderActivity.class);
				intent.putExtra("type_id", type_id);
				startActivityForResult(intent, 0);
			}
		});
	}
	/**
	 * 初始化菜品类型
	 */
	private void initViews_MenuType() {
		// 获取菜品类型数据
		lstDate_MenuType = new MenuTypeManager(this).queryMenuTypes();
		// 添加菜品类型
		for (int i = 0; i < lstDate_MenuType.size(); i++) {
			final Button button = new Button(this);
			button.setTag(i);
			if (i == 0) {
				button.setTextColor(Color.WHITE);
			}
			button.setBackgroundColor(Color.parseColor("#E78E29"));
			button.setText(lstDate_MenuType.get(i).getName());
			button.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int position = ((Integer) button.getTag()) + 1;
					type_id=position;
					// 为GridView绑定数据
					initViews_Menu(position);
					for (int j = 0; j < button_menuTypes.size(); j++) {
						button_menuTypes.get(j).setTextColor(Color.BLACK);
					}
					button.setTextColor(Color.WHITE);
				}
			});

			button_menuTypes.add(button);
			// 将组件对象放置在布局管理器中
			menuTypes.addView(button, i);
		}
	}
	/**
	 * 添加GridView
	 */
	private void initViews_Menu(int type_id) {
		lstDate = new MenuManager(this).queryMenus(type_id);
		PageCount = (int) Math.ceil(lstDate.size() / PAGE_SIZE);
		if (gridView != null) {
			curPage.removeAllViews();
		}
		for (int i = 0; i < PageCount; i++) {
			gridView = new GridView(MenuActivity.this);
			gridView.setAdapter(new DateAdapter(MenuActivity.this, lstDate, i,textview_menuDesc));
			gridView.setNumColumns(4);
			gridView.setHorizontalSpacing(8);
			gridView.setVerticalSpacing(8);
			// 去掉点击时的黄色背景
			gridView.setSelector(R.drawable.bg_grid_item);
			gridView.setOnItemClickListener(gridListener);
			curPage.addView(gridView);
		}
	}

	

	


	/**
	 * GridView的监听事件
	 */
	public OnItemClickListener gridListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			PageCurrent = curPage.getCurScreen();
			gridID = arg2 + PageCurrent * 12;

			if (((GridView) arg0).getTag() != null) {
				((View) ((GridView) arg0).getTag()).setBackgroundResource(R.drawable.bg_grid_item);
			}
			((GridView) arg0).setTag(arg1);
			arg1.setBackgroundResource(R.drawable.bg_grid_item_false);
		}
	};

	/**
	 * 更新当前页码
	 */
	public void setCurPage(int page) {
		layoutBottom.removeAllViews();
		for (int i = 0; i < PageCount; i++) {
			imgCur = new ImageView(MenuActivity.this);
			imgCur.setBackgroundResource(R.drawable.bg_img_item);
			imgCur.setId(i);
			// 判断当前页码来更新
			if (imgCur.getId() == page) {
				imgCur.setBackgroundResource(R.drawable.bg_img_item_true);
			}
			layoutBottom.addView(imgCur);
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
		case RESULT_OK:
			Bundle b=data.getExtras();  //data为B中回传的Intent
			Integer type_id=b.getInt("type_id");//str即为回传的值"Hello, this is B speaking"
			initViews_Menu(type_id);
			break;
		default:
		    break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	
	// 捕捉按键事件
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// 建立菜单选项
	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		getMenuInflater().inflate(R.menu.options_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	// 处理菜单选项
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.quit:
			// 取得自定义View
			LayoutInflater layoutInflater = LayoutInflater.from(MenuActivity.this);
			final View logout_View = layoutInflater.inflate(R.layout.logout, null);

			Dialog alertDialog = new AlertDialog.Builder(MenuActivity.this)
					.setTitle("确认退出吗？").setIcon(R.drawable.call).setView(logout_View)
					.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//TODO 检查用户密码是否正确
							// 获得服务员工号,查找本地用户信息
							String account = findUserMsg();
							// 获得密码
							String password = ((TextView)logout_View.findViewById(R.id.edittext_logout_password)).getText().toString();
							
							User user=new UserManager(MenuActivity.this).query(account, password);
							if(user!=null){
								//清空订单信息
								new OrderDetailManager(MenuActivity.this).truncate();
								//删除本地用户信息
								deleteUserMsg();
								//关闭背景音乐
								stopService(new Intent("com.liuwang.meal.MUSIC"));
								//关闭所有Activity
								MyApplication.getInstance().exit();
							}else{
								MyUtil.showDialog(MenuActivity.this, "密码错误，退出失败");
							}
						}
					}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							
						}
					}).create();
			alertDialog.show();
			
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}


	// 查找配置文件中的用户信息
	private String findUserMsg(){
		// 共享信息
		SharedPreferences sp = getSharedPreferences("user_msg", MODE_WORLD_WRITEABLE);
		return sp.getString("account", "");
	}
	// 清空配置文件中的用户信息
	private void deleteUserMsg(){
		// 共享信息
		SharedPreferences sp = getSharedPreferences("user_msg", MODE_WORLD_WRITEABLE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("account", "");
		editor.commit();
	}
}